/*
 * Authors: Alex Attar & Kevin El Hage
 * ID: 9765727
 * Date: 9/3/2012
 * 
 */

package taskManagerSystem.ControllerSubsystem;

import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JOptionPane;

import taskManagerSystem.ModelSubsystem.Model;
import taskManagerSystem.ViewSubsystem.View;

/* This class will prompt the user to save a file before exiting when 
 * the user is exiting from the window (and not from the exit menu).
 * If any changes have been made to the task table and the user clicks on
 * the 'X' on the window, a pop up will appear prompting the user to either
 * save before exiting ("Yes"), exit without saving ("No"), or cancel
 * the operation and thus stay with the window open ("Cancel")
 */

public class WindowSaveOnExitListener extends WindowAdapter {
	protected Model model;
	protected View view;

	//constructor
	public WindowSaveOnExitListener(Model model, View view) {
		this.model = model;
		this.view = view;
	}	

	/* function that checks if any changes were made to the task table;
	 * if any were made, pops up a small window prompting the user to 
	 * see if he/she wants to save a file.
	 * The pop up gives the user 3 choices:
	 *- to save before exiting, in which case all changes are saved
	 * to the specific file
	 *- to exit without saving, in which case
	 * the program exits without saving changes,
	 *- to cancel, in which case nothing happens
	 */
	public void windowClosing(WindowEvent e) {
		//if changes have been made inside the task table and the user has
		//clicked on the 'X' in the window, pop up another window
		//to prompt the user for action before exiting. Else, simply exit when user clicks
		if(model.hasChanged() == true) {
			int option = JOptionPane.showOptionDialog((Component) e.getSource(), 
					"Do you want to save before exiting?", 
					"Save On Exit", JOptionPane.YES_NO_CANCEL_OPTION,
					JOptionPane.WARNING_MESSAGE, null, null, null);

			//if user clicks on "Yes", changes are saved to the file and
			//the program exits. Else if user clicks on "No", the system 
			//exits without modifying the file
			if(option == JOptionPane.YES_OPTION) {
				JFileChooser filesave = new JFileChooser();
				FileFilter filter = new FileNameExtensionFilter("XML Tasks file", "xml");
				filesave.addChoosableFileFilter(filter);

				int ret = filesave.showSaveDialog(null);

				if (ret == JFileChooser.APPROVE_OPTION){
					File file = filesave.getSelectedFile();
					String filename = file.getPath();
					model.saveData(filename);
					System.exit(0);
				}
			} else if(option == JOptionPane.NO_OPTION) {
				System.exit(0);
			}
		}else if(model.hasChanged() == false){
			System.exit(0);
		}
	}
}


